<?php

/*
 * Класс, инкапсулирующий логику отношений "многие-к-одному"
 */

namespace T4\MODEL\RELATIONS\MYSQL;
use T4\MODEL\AdapterCollection;

class ManyToOne {
	
	protected $adapter;
	protected $name;
	protected $definition;

	public function __construct($adapter, $name, $definition) {
		$this->adapter = $adapter;
		$this->name = $name;
		$this->definition = $definition;
	}
	
	public function getComment() {
		return isset($this->definition['comment']) ? $this->definition['comment'] : '';
	}
	
	public function getRelationColumnName() {
		return '__' . $this->name . '_id';
	}
	
	public function getRelationColumnDDL() {
		return '`' . $this->getRelationColumnName() . '` INT UNSIGNED NOT NULL DEFAULT \'0\' COMMENT \'' . $this->getComment() . '\'';
	}

	public function getRelationIndexDDL() {
		return 'KEY `' . $this->getRelationColumnName() . '` (`' . $this->getRelationColumnName() . '`)';
	}
	
	public function getTablesJoin() {
		$modelClassName = $this->definition['model'];
		$table = $modelClassName::getTable();
        return
			'LEFT JOIN `' . $table . '` 
				ON `' . $table . '`.`' . $modelClassName::PRIMARY_KEY .'`=`' . $this->adapter->getTable() . '`.`' . $this->getRelationColumnName() . '`';

	}
	
	public function getColumnsList() {
		$modelClassName = $this->definition['model'];
		return AdapterCollection::getInstance($modelClassName)->prepareColumnList();
	}
	
}